package com.cbl.v.ssczs.mode.util;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class Tools {
    public static boolean isShow = true;

    /**
     * 读取assent中的json文件
     *
     * @param mContext
     * @param fileName
     * @return
     */
    public static String getJson(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }


    /**
     * 获取版本号名称给用户看的
     *
     * @param context
     * @return
     */
    public static String getCurrentVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            String packageName = context.getPackageName();
            PackageInfo inPackageInfo = packageManager.getPackageInfo(packageName, 0);
            String Version = inPackageInfo.versionName;
            return Version;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本号用来比较版本的升级
     *
     * @param context
     * @return
     */
    public static int getCurrentVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            String packageName = context.getPackageName();
            PackageInfo inPackageInfo = packageManager.getPackageInfo(packageName, 0);
            return inPackageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 吐司方法
     *
     * @param context
     * @return
     */
    public static void ShowInfo(Context context, String text) {
        if (isShow) {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 将Bitmap转换成Base64字符串
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64String(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    /**
     * 获取手机的语言环境
     *
     * @param context
     * @return
     */
    public static String getLanguage(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        return language;
    }

    /**
     * 对字符串进行URL编码
     *
     * @param url
     * @return
     */
    public static String getURLCode(String url) {
        String link = URLEncoder.encode(url);
        return link;
    }

    /**
     * 判断用户手机是否安装了微信
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (packageInfoList != null) {
            for (int i = 0; i < packageInfoList.size(); i++) {
                String pn = packageInfoList.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断用户手机是否安装了手机QQ
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
        if (packageInfoList != null) {
            for (int i = 0; i < packageInfoList.size(); i++) {
                String pn = packageInfoList.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 启动手机QQ的聊天界面
     */
    public static void startQQ(Context context, String qq) {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    /**
     * 启动拨打电话
     */
    public static void startCall(Context context, String phoneNumber) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);//指定意图动作
        intent.setData(Uri.parse("tel:" + phoneNumber));//指定电话号码
        context.startActivity(intent);
    }

    /**
     * 发送邮件
     */
    public static void sendMail(Context context, String mailAddress) {
        Intent data = new Intent(Intent.ACTION_SENDTO);
        data.setData(Uri.parse("mailto:" + mailAddress));
        data.putExtra(Intent.EXTRA_SUBJECT, "请在这里填写标题");
        data.putExtra(Intent.EXTRA_TEXT, "请在这里填写内容");
        context.startActivity(data);
    }


    /**
     * 点击弹出时间选择框，并传入控件选择完成则在控件上显示时间
     *
     * @param context
     * @return
     */
    public static void showDatePickerDialog(Context context, final Button button) {
        final Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                c.set(year, monthOfYear, dayOfMonth);
                button.setText(DateFormat.format("yyy-MM-dd HH:mm:ss:ff", c));
            }
        },
                c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * 判断是否有网络，给用户提示
     *
     * @param activity
     * @return
     */
    public static void checkNetwork(final Activity activity) {
        ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null) {
            Tools.ShowInfo(activity, "请连接网络再试");
        }
    }

    /**
     * 初始化webiew的配置
     *
     * @param webView
     */
    public static void initWebView(WebView webView) {
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSavePassword(false);
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }
        });
    }


    /**
     * 弹出软键盘
     *
     * @param editText
     * @param activity
     */
    public static void showSoftInput(EditText editText, Activity activity) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, 0);
    }

    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hideSoftInput(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }


    public static String getDouble(double d) {
        BigDecimal b = new BigDecimal(d);
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String getDoubleToString(double d, int value) {
        BigDecimal b = new BigDecimal(d);
        return b.setScale(value, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String getMoneyDoubleToString(double d, int value) {
        BigDecimal b = new BigDecimal(d);
        return "¥" + b.setScale(value, BigDecimal.ROUND_HALF_UP).toString();
    }


    /**
     * 获取评价者姓名
     *
     * @param name
     * @return
     */
    public static String getEvaluateName(String name) {
        StringBuilder userName = new StringBuilder();
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 2) {
                for (int i = 0; i < name.length(); i++) {
                    if (i == 0) {
                        userName.append(name.substring(0, 1));
                    } else if (i == name.length() - 1) {
                        userName.append(name.substring(name.length() - 1));
                    } else {
                        userName.append("*");
                    }
                }
            } else if (name.length() == 2) {
                userName.append(name.substring(0, 1));
                userName.append("*");
            } else {
                userName.append(name);
            }
        }
        return userName.toString();
    }

    /**
     * 将银行卡名字替换*
     *
     * @param bankNumber
     * @return
     */
    public static String getBankNumber(String bankNumber) {
        StringBuffer number = new StringBuffer();
        int size = bankNumber.trim().length();
        for (int i = 0; i < size; i++) {
            if (size - i > 3) {
                number.append("*");
            } else if (i == size - 1) {
                String m = bankNumber.substring(size - 4, size - 1);
                number.append(m);
            }
            if (i % 4 == 0) {
                number.append(" ");
            }
        }
        return number.toString();
    }

    /**
     * 获取拼接字符串
     *
     * @param list
     * @return
     */
    public static String getStringSplitValue(List<String> list) {
        StringBuilder builder = new StringBuilder();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    builder.append(list.get(i));
                } else {
                    builder.append(list.get(i) + ",");
                }
            }
        }
        return builder.toString();
    }

    /**
     * 将用逗号分隔开的数值转为数组
     *
     * @param value
     * @return
     */
    public static List<String> getListStringSplitValue(String value) {
        if (!TextUtils.isEmpty(value)) {
            String[] list = value.split(",");
            return Arrays.asList(list);
        }
        return null;
    }


    /**
     * 跳转到应用市场
     *
     * @param context
     */
    public static void goAppMarket(Context context) {
        if (isAvilible(context, "com.tencent.android.qqdownloader")) {
            launchAppDetail(context, "com.shop.ddgo", "com.tencent.android.qqdownloader");
        } else {
            Uri uri = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=" + "com.shop.ddgo");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        }
    }

    /**
     * 启动到app应用界面
     *
     * @param appPkg    App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断市场是否存在的方法
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }


    /**
     * 判断是否有网络，如果没有则跳转到开启页面
     *
     * @param activity
     * @return
     */
    public static boolean checkNetworkCanble(final Activity activity) {
        ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null) {
            new AlertDialog.Builder(activity)
                    .setMessage("亲，你还没有连上网络")
                    .setCancelable(false)
                    .setPositiveButton("点击联网", new DialogInterface.OnClickListener() {

                        @SuppressWarnings("unused")
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //	int asVersion=android.os.Build.VERSION.SDK_INT;
                            int asVersion = Build.VERSION.SDK_INT;
                            Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                            activity.startActivity(intent);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();

                }
            }).show();
            return false;
        }
        return true;
    }

    /**
     * 倒计时类
     *
     * @param btVerify
     * @return
     */
    public static CountDownTimer getTimeCount(final Button btVerify) {
        /**
         * TODO 计时器 定义一个倒计时的内部类
         */
        class TimeCount extends CountDownTimer {

            public TimeCount(long millisInFuture, long countDownInterval) {
                super(millisInFuture, countDownInterval);
            }

            @Override
            public void onFinish() {
                btVerify.setText("重新获取");
                btVerify.setEnabled(true);
            }

            @Override
            public void onTick(long millisUntilFinished) {
                String text = millisUntilFinished / 1000 + "s";
                btVerify.setText(text);
                btVerify.setEnabled(false);
            }
        }
        return new TimeCount(60 * 1000, 1000);
    }

    /***
     * 获取定位信息
     * @param activity
     * @return
     */
    public static Location getLocation(Activity activity) {
        String locationProvider = null;
        LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            Log.i("定位", "GPS");
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            Log.i("定位", "Network");
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Log.i("定位", "为空");
            Tools.ShowInfo(activity, "不能获取定位信息");
        }
        //Location location = locationManager.getLastKnownLocation(locationProvider);
        Location location = null;
        if (location != null) {
            Log.i("定位", "location不为空");
            return location;
        } else {
            Log.i("定位", "location为空");
        }
        return null;
    }


}




	

